﻿using Newtonsoft.Json;
using RestSharp;
using System;
using System.Diagnostics;
using System.IO;
using System.Linq;
using System.Net;
using System.Text;

namespace LService.Net.Net.Rest
{
    /// <summary>
    /// Class RestHelper.
    /// </summary>
    public static class RestHelper
    {
        #region 属性

        /// <summary>
        /// The HTTP
        /// </summary>
        private const string HTTP = "http://";

        /// <summary>
        /// The HTTPS
        /// </summary>
        private const string HTTPS = "https://";

        /// <summary>
        /// The HTTP string
        /// </summary>
        private static string httpStr;

        #endregion

        #region 构造

        /// <summary>
        /// Initializes static members of the <see cref="RestHelper"/> class.
        /// </summary>
        static RestHelper()
        {
            ServicePointManager.DefaultConnectionLimit = 50;
            httpStr = HTTP + "";//baseUrl

            if (!string.IsNullOrWhiteSpace(""))   //端口
            {
                httpStr += ":" + "";
            }
            if (!string.IsNullOrWhiteSpace("")) //接口URL
            {
                httpStr += "/" + "";
            }
        }

        #endregion

        #region 方法

        /// <summary>
        /// Gets the parameter.
        /// </summary>
        /// <typeparam name="T"></typeparam>
        /// <param name="dics">The dics.</param>
        /// <returns>System.String.</returns>
        public static string GetParam<T>(T dics)
        {
            try
            {
                RestResponse<object, T> response = new RestResponse<object, T>();
                response.header = new RestHeaderResult();
                response.header.v = "1.0.0";
                response.header.type = "PC";
                response.header.imei = Guid.NewGuid().ToString();
                response.body = new RestBodyResult<object, T>();
                response.body.code = new object();
                response.body.content = new object();
                response.body.param = dics;
                //return JsonConvert.SerializeObject(response, Formatting.Indented, new JsonSerializerSettings { NullValueHandling = NullValueHandling.Ignore });
                return JsonConvert.SerializeObject(response);
            }
            catch (Exception ex)
            {
                Trace.TraceError(ex.Message);
            }
            return null;
        }

        /// <summary>
        /// HTTPs the web request by get.
        /// </summary>
        /// <typeparam name="TContent">The type of the t content.</typeparam>
        /// <typeparam name="TParameter">The type of the t parameter.</typeparam>
        /// <param name="url">The URL.</param>
        /// <returns>RestResponse&lt;TContent, TParameter&gt;.</returns>
        public static RestResponse<TContent, TParameter> HttpWebRequestByGet<TContent, TParameter>(string url)
        {
            RestResponse<TContent, TParameter> keyResponse = new RestResponse<TContent, TParameter>();
            if (url.Contains('+'))
                url = url.Replace("+", "%2B");
            if (url.Contains('#'))
                url = url.Replace("#", "%23");
            if (url.Contains('&'))
                url = url.Replace("&", "%26");
            if (url.Contains('!'))
                url = url.Replace("!", "%21");

            HttpWebRequest request = (HttpWebRequest)WebRequest.Create(httpStr + url);
            request.Method = "Get";
            request.Timeout = 1000 * 10;
            using (HttpWebResponse response = (HttpWebResponse)request.GetResponse())
            {
                using (StreamReader reader = new StreamReader(response.GetResponseStream(), Encoding.UTF8))
                {
                    string responseData = reader.ReadToEnd();
                    keyResponse = JsonConvert.DeserializeObject<RestResponse<TContent, TParameter>>(responseData);
                }
            }

            return keyResponse;
        }

        /// <summary>
        /// HTTPs the web request by post.
        /// </summary>
        /// <typeparam name="TContent">The type of the t content.</typeparam>
        /// <typeparam name="TParameter">The type of the t parameter.</typeparam>
        /// <param name="url">The URL.</param>
        /// <param name="para">The para.</param>
        /// <returns>RestResponse&lt;TContent, TParameter&gt;.</returns>
        public static RestResponse<TContent, TParameter> HttpWebRequestByPost<TContent, TParameter>(string url, string para)
        {
            RestResponse<TContent, TParameter> keyResponse;

            var client = new RestClient(httpStr + url);
            var request = new RestRequest(Method.POST);
            request.AddHeader("", "");
            request.AddParameter("", ParameterType.RequestBody);
            IRestResponse response = client.Execute(request);
            keyResponse = JsonConvert.DeserializeObject<RestResponse<TContent, TParameter>>(response.Content);

            return keyResponse;
        }

        /// <summary>
        /// 网络地址是否存在.
        /// </summary>
        /// <param name="URL">The URL.</param>
        /// <returns><c>true</c> if XXXX, <c>false</c> otherwise.</returns>
        public static bool UrlIsExist(string URL)
        {
            HttpWebRequest req = null;
            HttpWebResponse res = null;
            try
            {
                req = (HttpWebRequest)WebRequest.Create(URL);
                req.Method = "HEAD";
                req.Timeout = 1000;
                res = (HttpWebResponse)req.GetResponse();
                return (res.StatusCode == HttpStatusCode.OK);
            }
            catch
            {
                return false;
            }
            finally
            {
                if (res != null)
                {
                    res.Close();
                    res = null;
                }
                if (req != null)
                {
                    req.Abort();
                    req = null;
                }
            }
        }

        #endregion
    }
}